import { Strategy, ExtractJwt, StrategyOptions } from 'passport-jwt';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Request } from 'express';
import { CacheService } from 'src/tools/redis/redis.cache.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private redisService: CacheService) {
    super({
      jwtFromRequest: ExtractJwt.fromHeader('token'), //使用ExtractJwt.fromHeader从header获取token
      ignoreExpiration: false, //如果为true，则不验证令牌的过期时间。
      secretOrKey: process.env.SECRET, //使用密钥解析，可以使用process.env.xxx
      passReqToCallback: true,
    } as StrategyOptions);
  }

  //token验证, payload是super中已经解析好的token信息
  async validate(req: Request, payload: any) {
    const { id } = payload;
    const token = ExtractJwt.fromHeader('token')(req);
    const cacheToken = await this.redisService.get(`user-token-${id}`);  //获取redis的key
    // 单点登陆验证
    if (token !== JSON.parse(cacheToken)) {
      throw new HttpException('你没有权限访问,请联系管理员', HttpStatus.UNAUTHORIZED);
    }
    return { username: payload.username,id:  payload.id};
  }
}